# -*- coding: UTF-8 -*-
"""
遍历out文件夹中的子文件夹, 将子文件中的text文件内容以及文件名中的RGB颜色值(6个十六进制字符)
逐一复制到剪贴板(除info文件外), 方便发送高级弹幕
"""
import os
import sys
import re
import win32clipboard as wc
import DCAMParser


def cp_to_clipboard(txt):
    """
    将文本复制到系统剪贴板
    :param txt: 要复制到剪贴板的文本
    :return: 无
    """
    wc.OpenClipboard()
    wc.EmptyClipboard()
    wc.SetClipboardText(txt, wc.CF_UNICODETEXT)
    wc.CloseClipboard()


def cp_txt(txt_color):
    """
    复制文本内容和对应颜色到剪贴板
    :param txt_color: 要复制的文本和颜色
    :return: 无
    """
    txt, color = txt_color

    if txt is None:
        print("跳过此文件")
        return
    elif txt == "dcam":
        return

    cp_to_clipboard(txt)
    print("---->已将文件内容复制到剪贴板！\n")
    input(" >>> 粘贴后再按回车键(Enter键)继续复制对应颜色值")
    print("")
    if color is not None:
        cp_to_clipboard(color)
        print("---->已将颜色值复制到剪贴板！\n")
        input(" >>> 粘贴后再按回车键(Enter键)继续")
        print("")


def read_file(entry):
    """
    读取entry指定的文件内容
    :param entry: 要读的文件
    :return: buffer: 文件内容, color: 如果文件名开头有对应的颜色的RGB值则返回之
    """
    buffer = None
    color = None
    file_name = entry.name
    print('---------------------')
    print(f"检查文件：{file_name}")

    dot_pos = file_name.rfind('.')
    primary = file_name[0:dot_pos]
    suffix = file_name[dot_pos + 1:]

    if file_name != "info.txt":
        if suffix == "txt":
            # 判断文件名中是否有RGB或RGBA通道颜色值(6或8个十六进制数)
            pattern_rgb = r"^[0-9a-fA-F]{6}"
            pattern_rgba = r"^[0-9a-fA-F]{8}"
            res_rgb = re.match(pattern_rgb, primary)
            res_rgba = re.match(pattern_rgba, primary)
            if res_rgba is not None:
                color = res_rgba.group()
                print(f"颜色为: {color}")
                print("")
            elif res_rgb is not None:
                color = res_rgb.group()
                print(f"颜色为: {color}")
                print("")
            else:
                return None, None

            with open(entry, "r", encoding='utf-8-sig', errors='ignore') as f:
                line = f.readline()
                buffer = line
                while line:
                    line = f.readline()
                    buffer += line

        elif suffix == "xml":
            dcam = DCAMParser.DcamParser(entry)
            for item in dcam:
                buffer = item['chars']
                color = item['color']
                name = item['name']
                idx = item['index']
                if name is None:
                    print(f"\n正在复制第 {idx:d} 图层, 颜色为：{color}\n")
                else:
                    print(f"\n正在复制第{idx}图层[{name}], 颜色为：{color}\n")

                cp_txt((buffer, color))
            buffer = "dcam"

    return buffer, color


def proc_out_dir(out_dir="./out"):
    """
    遍历out_dir指定的目录中的字符文本文件
    :param out_dir:
    :return:
    """
    if not os.path.exists(out_dir):
        print(f'找不到弹幕文本文件目录："{out_dir}"')
        input(" >>> 按回车键(Enter键)退出")
        sys.exit(-1)

    for entry in os.scandir(out_dir):
        if os.path.isdir(entry):
            print("******************************")
            print(f"处理目录：{entry.name}")
            print("******************************")
            for sub_entry in os.scandir(entry):
                if os.path.isfile(sub_entry):
                    cp_txt(read_file(sub_entry))
        elif os.path.isfile(entry):
            if os.path.isfile(entry):
                cp_txt(read_file(entry))


def logo():
    print("===================================")
    print("AcFun高级弹幕弹幕画文件复制助手(V1.3)")
    print("===================================")
    print("")


def show_fin_info():
    print('\n---------------------')
    print("处理完毕!")
    print("")
    input(" >>> 按回车键(Enter键)退出")


if __name__ == "__main__":
    logo()

    out_dir = "./out"

    proc_out_dir(out_dir)

    show_fin_info()

